import axios from 'axios'
import { Loading } from 'element-ui'
import qs from 'qs'
import global from '../common/Global'
import router from '../router'
import { Message } from 'element-ui';

// axios 配置
axios.defaults.timeout = 10000
axios.defaults.baseURL = global.API
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let loading = null // 定义loading变量
function startLoading () { // 使用Element loading-start 方法
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading () { // 使用Element loading-close 方法
  if (loading !== null) {
    loading.close()
  }
}

let needLoadingRequestCount = 0
let delayTime = 500
let delayTimeoutId = 0

export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    delayTimeoutId = setTimeout(function () {
      startLoading()
    }, delayTime) // 延迟显示，当请求响应时间过快时不需要显示loading
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    window.clearTimeout(delayTimeoutId)
    endLoading()
  }
}

// http request 拦截器
axios.interceptors.request.use(
  config => {
    showFullScreenLoading()
    let token = sessionStorage.getItem('token')
    if (token) {
      config.headers.token = token
    }
    let contentType = config.headers['Content-Type']
    if (typeof (contentType) === 'undefined') {
      config.transformRequest = [
        function (obj) {
          return qs.stringify(obj)
        }]
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

// http response 拦截器
axios.interceptors.response.use(
  response => {
    tryHideFullScreenLoading()
    let contentType = response.headers['content-type']
    // console.log('response403', contentType);
    if (typeof (contentType) !== 'undefined' &&
      contentType.indexOf('application/json') > -1) {
      //
    } else if (typeof (contentType) !== 'undefined' &&
      contentType.indexOf('text/html') > -1) {
      // console.log('response.data', response.data);
      if (typeof (response.data) !== 'undefined' &&
        response.data.indexOf('<title>403')) {
        router.replace({
          path: 'login',
          query: {redirect: router.currentRoute.fullPath}
        })
      }
    }

    return response
  },
  error => {
    tryHideFullScreenLoading()
    if (error.response) {
      // console.log('axios.error:', error)
      switch (error.response.status) {
        case 404:
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
          break
        case 413:
          Message.error('输入有误，请重新输入')
          break
        case 401:
          // 401 清除token信息并跳转到登录页面
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
          break
        case 500:
          // console.log('500', error)
          router.replace('500')
          break
      }
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response.data)
  })

export default axios
